import React, { useState, useEffect } from 'react';
import { Table, Space, Button, Divider, Modal, Input, DatePicker, Popconfirm, Select, } from 'antd';
import moment from 'moment';
import * as appStyles from './app.module.css';

const { Option } = Select,
  { TextArea } = Input,
  newTitle = <span style={{ fontWeight: 'bold' }}>新建任务</span>,
  editTitle = (id = '') => <span style={{ fontWeight: 'bold' }}>编辑任务( ID: {id} )</span>,
  urlHost = '127.0.0.1',
  statusObj = {
    1: {
      name: '待办',
      color: '#f5222d',
    },
    2: {
      name: '完成',
      color: '#52c41a',
    },
    3: {
      name: '进行中',
      color: '#1890ff',
    },
  },
  initObj = {
    deadline: '',
    name: '',
    status: 1,
  },
  // 后端端口
  backendPort = 9999;


function App(props) {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isCreate, setIsCreate] = useState(false);
  const [editingRecordInfo, setEditingRecordInfo] = useState(null);
  const [tableDataSource, setTableDataSource] = useState([]);


  // 获取全部任务
  const getAllTaskList = () => {
    fetch(`http://${urlHost}:${backendPort}/list/-1/1`)
      .then(res => {
        if (!res) throw new Error('无列表数据...');
        return res.json();
      })
      .then(data => {
        const arr = data?.['list']?.['rows'] || [];
        for (let v of arr) {
          v.key = v.id;
          v.deadline = String(v.deadline).slice(0, 10);
        }
        setTableDataSource(arr);
      })
      .catch(err => { })
  }

  useEffect(() => {
    getAllTaskList();
  }, [])


  const commonFetch = (urlPathname, obj, callback = () => { }, failInfo = '') => {
    const options = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(obj)
    }
    fetch(`http://${urlHost}:${backendPort}/${urlPathname}`, options)
      .then(res => {
        console.log('res', res);
        if (!res) throw new Error('无列表数据...');
        return res.json();
      })
      .then(data => {
        console.log('data', data);
        if (data) {
          callback();
        }
      })
      .catch(err => { })
  }


  const showModal = () => {
    setIsModalVisible(true);
  };


  const handleModalOk = () => {
    const bool = Object.values(editingRecordInfo).reduce((a, b) => a && b, true);
    if (bool) {
      if (isCreate) {
        commonFetch(
          'create',
          {
            "name": editingRecordInfo.name,
            "deadline": editingRecordInfo.deadline,
            "content": editingRecordInfo.content,
            "status": 1
          },
          () => {
            getAllTaskList();
          }
        )
      } else {
        if (editingRecordInfo) {
          commonFetch(
            'update',
            {
              "id": editingRecordInfo.id,
              "name": editingRecordInfo.name,
              "deadline": editingRecordInfo.deadline,
              "content": editingRecordInfo.content
            },
            () => {
              getAllTaskList();
            }
          )
        }
      }
      setIsModalVisible(false);
    }
  };


  const handleModalCancel = () => {
    setIsModalVisible(false);
  };


  const onInputChange = (v) => {
    const val = v?.target?.value;
    const tempObj = { ...editingRecordInfo };
    tempObj.name = val;
    setEditingRecordInfo(tempObj);
  }


  const onDatePickerChange = (date, dateString) => {
    const tempObj = { ...editingRecordInfo };
    tempObj.deadline = dateString;
    setEditingRecordInfo(tempObj);
  }


  const handleTextAreaChange = (v) => {
    const val = v?.target?.value;
    const tempObj = { ...editingRecordInfo };
    tempObj.content = val;
    setEditingRecordInfo(tempObj);
  }


  const handleSelectChange = (v, id) => {
    if (!v || !id) return;
    commonFetch(
      'update_status',
      {
        id,
        "status": v
      },
      () => {
        getAllTaskList();
      }
    )
  }


  const handleDeleteTask = (k) => {
    if (k) {
      commonFetch(
        'delete',
        { id: k },
        () => {
          getAllTaskList();
        }
      )
    }
  }


  const columns = [
    {
      title: 'ID',
      dataIndex: 'id',
      key: 'id',
      align: 'center',
    },
    {
      title: '标题',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    {
      title: '内容',
      dataIndex: 'content',
      key: 'content',
      align: 'center',
    },
    {
      title: '截止日期',
      dataIndex: 'deadline',
      key: 'deadline',
      align: 'center',
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      align: 'center',
      filters: [
        {
          text: '待办',
          value: 1,
        },
        {
          text: '完成',
          value: 2,
        },
        {
          text: '进行中',
          value: 3,
        },
      ],
      filtered: true,
      onFilter: (value, record) => record.status === value,
      render: (text, record) => {
        return <Select
          size="small"
          defaultValue={statusObj[text]['name']}
          style={{ width: 100, color: statusObj[text]['color'] || '#000' }}
          bordered={false}
          onChange={(e) => handleSelectChange(e, record.id)}
        >
          <Option value={1} style={{ color: statusObj[1]['color'] }}>{statusObj[1]['name']}</Option>
          <Option value={2} style={{ color: statusObj[2]['color'] }}>{statusObj[2]['name']}</Option>
          <Option value={3} style={{ color: statusObj[3]['color'] }}>{statusObj[3]['name']}</Option>
        </Select>
      }
    },
    {
      title: '操作',
      key: 'action',
      align: 'center',
      render: (text, record) => (
        <Space size="middle">
          <Button
            type='primary'
            size='small'
            style={{ fontSize: 14 }}
            onClick={() => {
              setEditingRecordInfo(record);
              showModal();
              setIsCreate(false);
              taskNameInputGetFocus();
            }}
          >
            编辑
          </Button>
          <Button
            type='primary'
            size='small'
            style={{ fontSize: 14 }}

          >
            <Popconfirm
              title="确定要删除?"
              onConfirm={() => handleDeleteTask(record.id)}
              okText="确定"
              cancelText="取消"
            >
              删除
            </Popconfirm>
          </Button>
        </Space>
      ),
    },
  ];


  const taskNameInputGetFocus = () => {
    setTimeout(() => {
      const dom = document.getElementById('taskNameInput');
      if (dom) {
        dom.focus();
      }
    }, 0)
  }


  return (
    <div className={appStyles.appWrapper}>
      {/* 下划线 */}
      <Divider style={{ fontWeight: 'bold' }}>
        任务列表
      </Divider>
      {/* 新建按钮 */}
      <Button
        type='primary'
        onClick={() => {
          showModal();
          setIsCreate(true);
          setEditingRecordInfo(initObj);
          taskNameInputGetFocus();
        }}
        style={{ marginBottom: '0.5rem' }}
      >
        新建
      </Button>
      {/* 编辑时弹出的对话框 */}
      <Modal
        title={isCreate ? newTitle : editTitle(editingRecordInfo?.id)}
        visible={isModalVisible}
        closable={false}
        okText={'确定'}
        cancelText={'取消'}
        centered={true}
        onOk={handleModalOk}
        onCancel={handleModalCancel}
      >
        <div className={appStyles.modalContent}>
          <div className={appStyles.modalContentItem}>
            <span className={appStyles.modalContentStar}>*</span>
            任务名称：
          </div>
          <Input
            id='taskNameInput'
            size='middle'
            onChange={onInputChange}
            value={editingRecordInfo?.name || ''}
          />
        </div>
        <div className={appStyles.modalContent}>
          <div className={appStyles.modalContentItem}>
            <span className={appStyles.modalContentStar}>*</span>
            任务截止日期：
          </div>
          <DatePicker
            placeholder=''
            size='middle'
            value={(editingRecordInfo?.deadline) ? moment(editingRecordInfo?.deadline) : ''}
            onChange={onDatePickerChange}
            style={{ width: '100%' }}
            disabledDate={(currentDate) => {
              const now = new Date();
              now.setHours(0, 0, 0, 0);
              if (currentDate >= now) {
                return false;
              }
              return true;
            }}
          />
        </div>
        <div className={appStyles.modalContent}>
          <div className={appStyles.modalContentItem}>
            <span className={appStyles.modalContentStar}>*</span>
            任务内容：
          </div>
          <TextArea
            rows={5}
            value={editingRecordInfo?.content || ''}
            size='middle'
            autoSize={{ minRows: 5, maxRows: 10 }}
            onChange={handleTextAreaChange}
          />
        </div>
      </Modal>
      {/* 表格 */}
      <Table size='middle' columns={columns} dataSource={[...tableDataSource]} bordered pagination={{ position: ['bottomCenter'] }} />
    </div>
  );
}

export default App;